from py4j.java_gateway import JavaGateway, GatewayParameters


class ConnectJavaGatewayUtil:
    def __init__(self, host='localhost', port=25333):
        """
        初始化连接Java GatewayServer
        :param host: GatewayServer主机地址
        :param port: GatewayServer端口(默认25333)
        """
        self.gateway = JavaGateway(
            gateway_parameters=GatewayParameters(address=host, port=port)
        )
        self.service = self.gateway.entry_point

    def check_connect_opengauss_database(self, url, user, password):
        """
        连接OpenGauss数据库
        :param url: JDBC连接字符串 jdbc:opengauss://host:port/dbname
        :param user: 用户名
        :param password: 密码
        :return: 结果列表(json字符串)
        """
        # 检查数据库连通性
        return self.service.checkConnectOpenGaussDatabase(url, user, password)

    def execute_query_to_json_string(self, url, user, password, sql):
        """
        执行查询语句
        :param url: JDBC连接字符串 jdbc:opengauss://host:port/dbname
        :param user: 用户名
        :param password: 密码
        :param sql: SQL查询语句
        :return: 结果列表(json字符串)
        """
        return self.service.executeQueryToJsonString(url, user, password, sql)

    def execute_insert_update_delete(self, url, user, password, sql):
        """
        执行更新语句
        :param url: JDBC连接字符串 jdbc:opengauss://host:port/dbname
        :param user: 用户名
        :param password: 密码
        :param sql: SQL查询语句
        :return: 结果列表(json字符串)
        """
        return self.service.executeInsertUpdateDelete(url, user, password, sql)


# 使用示例
if __name__ == "__main__":
    # 1. 创建工具类的实例
    connectJavaGatewayUtil = ConnectJavaGatewayUtil()

    # 2. 检查数据库的连通性
    connect_result = connectJavaGatewayUtil.check_connect_opengauss_database(
        "jdbc:opengauss://7.203.172.41:8000/cpt_uat",
        "root",
        "TreasurySecurity_Cpt@54321"
    )
    print(f"数据库的连通情况：{connect_result}")

    # 3. 执行查询
    query_results = connectJavaGatewayUtil.execute_query_to_json_string(
        "jdbc:opengauss://7.203.172.41:8000/cpt_uat",
        "root",
        "TreasurySecurity_Cpt@54321",
        "SELECT * FROM users WHERE age > 30"
    )
    print(f"查询结果：{query_results}")

    # 4. 执行更新、删除
    update_or_insert_results = connectJavaGatewayUtil.execute_query_to_json_string(
        "jdbc:opengauss://7.203.172.41:8000/cpt_uat",
        "root",
        "TreasurySecurity_Cpt@54321",
        "update a_test_t_bak202510151132 set schemaname = 'aaa'"
    )
    print(f"执行更新、删除结果：{update_or_insert_results}")
